package com.jiufengxinxi.ts.common.utils.socket.client;

import com.jiufengxinxi.ts.device.equipment.test.ClinetSocketRequestHandle;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Michael Huang
 * 
 */
public class ChatClient extends Frame {
	MultiThreadClient multiThreadClient=null;
	ClinetSocketRequestHandle clinetSocketRequestHandle=new ClinetSocketRequestHandle();
	
	TextField tfTxt = new TextField();
	TextArea taContent = new TextArea();

	public static void main(String[] args) {
		new ChatClient().launchFrame(10004);
	}

	public void launchFrame(int port) {
		setLocation(400, 300);
		this.setSize(300, 300);
		add(tfTxt, BorderLayout.SOUTH);
		add(taContent, BorderLayout.NORTH);
		pack();
		this.addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent arg0) {
				disconnect();
				System.exit(0);
			}

		});
		tfTxt.addActionListener(new TFListener());
		setVisible(true);
		connect(port);
		clinetSocketRequestHandle.setTaContent(taContent);
	}

	public void connect(int port) {
		multiThreadClient=new MultiThreadClient("192.168.1.234",port);
		multiThreadClient.setSocketRequestHandle(clinetSocketRequestHandle);
		multiThreadClient.setSyn(true);
		//multiThreadClient.connection();
		//multiThreadClient.send("");
	}

	public void disconnect() {
		try{
			multiThreadClient.disconnect();
		}catch (Exception e) {
		}
		

	}

	private class TFListener implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			String str = tfTxt.getText().trim();
			taContent.setText(taContent.getText()+"\n"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss  ").format(new Date())+"发送信息："+str);
			tfTxt.setText("");
			//disconnect();
			//multiThreadClient.connection();
			taContent.setText(taContent.getText()+"\n"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss  ").format(new Date())+"收到信息："+multiThreadClient.send(str));

		}

	}
	
	
	

	/*private class RecvThread implements Runnable {

		public void start() {
			try {
				while (bConnected) {
					String str = dis.readUTF();
					taContent.setText(taContent.getText() + str + '\n');
				}
			} catch (SocketException e) {
				System.out.println("退出了，bye!");
			} catch (EOFException e) {
				System.out.println("退出了，bye!");
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}*/
}
